<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert show-icon :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类</span>
          <!--          选择商品分类的级联选择框-->
          <el-cascader expand-trigger="hover" :options="cateList" :props="cateProps"
                       v-model="selectedKeys" @change="parentCateChanged" clearable>

          </el-cascader>
        </el-col>
      </el-row>
      <!--          标签页面-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加参数
          </el-button>
          <!--          数据表格-->
          <el-table :data="tableData" border stripe>
            <!--            展开行-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="handClose(i,scope.row)" closable v-for="(item,i) in scope.row.attr_vals" :key="i">
                  {{ item }}
                </el-tag>
                <!--                输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--                添加的按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--            索引值-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row.attr_id)" icon="el-icon-edit">
                  编辑
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="adddialogVisible=true">添加属性
          </el-button>
          <!-- 数据表格-->
          <el-table :data="tableData" border stripe>
            <!--  展开行-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="handClose(i,scope.row)"  v-for="(item,i) in scope.row.attr_vals" :key="i">
                  {{ item }}
                </el-tag>
                <!--                输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!--                添加的按钮-->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!--            索引值-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="showEditDialog(scope.row.attr_id)" icon="el-icon-edit">
                  编辑
                </el-button>
                <el-button type="danger" size="mini" @click="removeParams(scope.row.attr_id)" icon="el-icon-delete">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!--    修改参数的对话框-->
    <el-dialog
      @close="editClose"
      :title="'修改'+titleText"
      :visible.sync="editdialogVisible">
      <!--      添加对话框的表单-->
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
    </el-dialog>
    <!--    添加参数的对话框-->
    <el-dialog
      @close="addClose"
      :title="'添加'+titleText"
      :visible.sync="adddialogVisible">
      <!--      添加对话框的表单-->
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  computed: {
    //计算对话框标题的文本
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    //如果按钮需要被禁用 返回true 否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    //当前选中的三级分类ID，用来获取参数
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      } else {
        return null
      }
    }
  },
  data() {
    return {
      //修改参数的表单数据
      editFrom: {},
      //编辑参数的对话框
      editdialogVisible: false,
      //验证规则
      addFromRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editFromRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      //添加属性的表单值
      addFrom: {
        attr_name: ''
      },
      //控制添加对话框的显示和隐藏
      adddialogVisible: false,
      //many和only的属性数据
      tableData: [],
      //被激活的页面的名称
      activeName: 'many',
      //商品分类列表
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
        // checkStrictly: true
      },
      //被选中的分类的值 被双向绑定
      selectedKeys: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //修改参数
    async saveAttrValues(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改成功！')
    },
    //删除参数
    handClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrValues(row)
    },
    //文本框失去焦点 或者按下了enter建
    handleInputConfirm(row) {
      //判断用户输入 trim去除两边的空格 判断长度是否为0 然后重置输入值 切换为button
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //输入合法了
      //将输入的值添加到attr_vals数组中
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      //保存到数据库中
      this.saveAttrValues(row)
    },
    //点击按钮展示输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获取焦点
      //$nextTick 作用是 当页面的元素重新被渲染时 执行回调函数
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    //删除参数
    async removeParams(attr_id) {
      //询问是否删除
      const res = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      //如果取消 返回 cancel
      //如果确定 返回 confirm
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: re } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
      if (re.meta.status !== 200) {
        return this.$message.error(re.meta.msg)
      }
      this.$message.success('删除参数成功！')
      this.getParams()
    },
    //修改按钮的关闭事件
    editClose() {
      this.$refs.editFromRef.resetFields()
    },
    //打开修改按钮的对话框
    async showEditDialog(id) {
      //根据参数ID查询参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editFrom = res.data
      this.editdialogVisible = true
    },
    //发起请求修改参数
    editParams() {
      this.$refs.editFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editFrom.attr_id}`, {
          attr_name: this.editFrom.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改参数成功！')
        this.editdialogVisible = false
        this.getParams()
      })
    },
    //发请求添加参数
    addParams() {
      // 表单验证
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addFrom.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加参数成功！')
        this.adddialogVisible = false
        this.getParams()
      })
    },
    //添加对话框的关闭事件
    addClose() {
      this.$refs.addFromRef.resetFields()
    },
    //获取所有分类
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.cateList = res.data
      // console.log(this.cateList)
    },
    //级联选择器被改变事件
    parentCateChanged() {
      //判断是否为三级标题
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.tableData = []
        return
      }
      // 当选择器改变时获取参数
      // console.log(this.selectedKeys)
      this.getParams()
    },
    //根据所选的分类ID获取对应的参数
    async getParams() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      //把attr_vals的字符串 改成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //文本框的显示和隐藏
        item.inputVisible = false
        //文本框的数据双向绑定
        item.inputValue = ''
      })
      console.log(res.data)
      this.tableData = res.data
    },
    //tab被点击的事件
    handleClick() {
      this.getParams()
    }
  }
}
</script>
<style type="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.input-new-tag {
  width: 120px;
}

.el-cascader {
  width: 100%;
}

.el-tag {
  margin: 10px;
}
</style>